package com.platform.cdcs.fragment.stock;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.MyApp;
import com.platform.cdcs.R;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.sherchen.slidetoggleheader.views.XListView;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by holytang on 2017/10/15.
 */
public class InStockFragment extends BaseFragment {

    private ItemAdapter adapter;
    private ObservableXListView listView;
    private String stockId;
    private int inType;
    private int pageIndex = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            stockId = getArguments().getString("stockId");
            inType = getArguments().getInt("inType");
        }
    }

    @Override
    public void initView(View view) {
        adapter = new ItemAdapter(getContext());
        initLoadImg(view.findViewById(R.id.load));
        hideThisToolBar(view);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        if (inType == 0) {
            setTitle("在途");
        } else if (inType == 1) {
            setTitle("在库");
        } else if (inType == 2) {
            setTitle("寄售");
        } else {
            setTitle("所有");
        }
        listView = (ObservableXListView) view.findViewById(android.R.id.list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //详情页面
                ProductList.ProductItem item = (ProductList.ProductItem) adapterView.getItemAtPosition(i);
                Bundle bundle = new Bundle();
                bundle.putString("stockId", stockId);
                bundle.putString("inType", String.valueOf(inType));
                bundle.putString("itemCode", item.getItemCode());
                bundle.putString("name", item.getItemName());
                bundle.putString("desc",item.getQty()+" "+item.getUom());
                FragmentUtil.navigateToInNewActivity(getActivity(), InStockDetailFrgment.class, bundle);
            }
        });
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                adapter.clear();
                adapter.notifyDataSetChanged();
                requestDetail(false);
            }

            @Override
            public void onLoadMore() {
                requestDetail(false);
            }
        });
        listView.setAdapter(adapter);
        requestDetail(true);
    }

    @Override
    public int layoutId() {
        return R.layout.listview;
    }

    private void requestDetail(boolean flag) {
        if (flag) {
            showLoadImg();
        }
        Map<String, String> param = new HashMap<>();
        param.put("stockId", stockId);
//        param.put("distCode", MyApp.getInstance().getAccount().getOrgId());
        param.put("subBUs",  getArguments().getString("subBUs"));
        param.put("itemCodes", getArguments().getString("itemCodes"));
        param.put("inType", String.valueOf(inType));
        param.put("pageSize", String.valueOf(Constant.PAGE_SIZE));
        param.put("pageIndex", String.valueOf(pageIndex));
        getHttpClient().post().url(Constant.DIST_SYS_STOCK_TAKEPRODUCTLST).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getActivity(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
//                dismissLoadImg();
                try {
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<InStockList>>() {
                    }.getType();
                    BaseObjResponse<InStockList> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        adapter.addAll(response.getResult().getDistSysStockTakeProductList());
                        adapter.notifyDataSetChanged();
                        if (response.getResult().getDistSysStockTakeProductList().size() == Constant.PAGE_SIZE) {
                            pageIndex++;
                            listView.setPullLoadEnable(true);
                        } else {
                            listView.setPullLoadEnable(false);
                        }
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    private class InStockList extends MockObj {
        private List<ProductList.ProductItem> distSysStockTakeProductList;

        public List<ProductList.ProductItem> getDistSysStockTakeProductList() {
            return distSysStockTakeProductList;
        }

        public void setDistSysStockTakeProductList(List<ProductList.ProductItem> distSysStockTakeProductList) {
            this.distSysStockTakeProductList = distSysStockTakeProductList;
        }

    }

    private class ItemAdapter extends EnhancedAdapter<ProductList.ProductItem> {

        public ItemAdapter(Context context) {
            super(context);
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            ViewHolder holder = (ViewHolder) paramView.getTag();
            ProductList.ProductItem item = getItem(position);
            holder.titleView.setText(item.getItemCode());
            holder.textView.setText(item.getItemName());
            holder.dateView.setText(String.format("%s %s", item.getQty(), item.getUom()));

        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            View rootView = null;
            rootView = inflater.inflate(R.layout.four_item, viewgroup, false);
            rootView.setBackgroundResource(R.drawable.shape_corner_center);
            ViewHolder holder = new ViewHolder();
            holder.titleView = (TextView) rootView.findViewById(R.id.title);
            holder.dateView = (TextView) rootView.findViewById(R.id.time);
            holder.textView = (TextView) rootView.findViewById(R.id.text);
            holder.textView.setSingleLine(false);
            holder.textView.setMaxLines(2);
            rootView.setTag(holder);
            return rootView;
        }

    }

    private class ViewHolder {
        TextView titleView, dateView, textView;
    }
}
